using System.Collections.Generic;
using System.Threading.Tasks;
using Admin.NET.Application.Entity.NoticeConfigs;
using Admin.NET.Application.Service.Emails.Dto;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using MimeKit;
using NewLife.Caching;
using SqlSugar;

namespace Admin.NET.Application.Service.Emails;

/// <summary>
/// 邮箱管理
/// </summary>
[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class EmailService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<EmailConfig> _rep;

	private readonly SqlSugarRepository<EmailRecord> _repRecord;

	private readonly ICache _cache;

	private readonly UserManager _userManager;

	public EmailService(SqlSugarRepository<EmailConfig> rep, ICache cache, UserManager userManager, SqlSugarRepository<EmailRecord> repRecord)
	{
		_rep = rep;
		_cache = cache;
		_userManager = userManager;
		_repRecord = repRecord;
	}

	/// <summary>
	/// 保存邮箱配置
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/email/save")]
	public async Task SaveSms(EmailConfigInput input)
	{
		EmailConfig config = await _rep.GetFirstAsync((EmailConfig f) => f.TenantId == (long?)_userManager.TenantId);
		if (config != null)
		{
			input.Id = config.Id;
		}
		EmailConfig entity = input.Adapt<EmailConfig>();
		await _rep.InsertOrUpdateAsync(entity);
	}

	/// <summary>
	/// 获取邮箱配置
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpGet("/email/detail")]
	public async Task<EmailConfig> SmsDetail()
	{
		return await _rep.GetFirstAsync((EmailConfig u) => u.TenantId == (long?)_userManager.TenantId);
	}

	/// <summary>
	/// 删除配置
	/// </summary>
	/// <returns></returns>
	[HttpPost("/email/delete")]
	public async Task DeleteSms()
	{
		await _rep.DeleteAsync((EmailConfig d) => d.TenantId == (long?)_userManager.TenantId);
	}

	/// <summary>
	/// 邮件流水
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpGet("/email/record/page")]
	public async Task<dynamic> Page([FromQuery] EmailRecordInput input)
	{
		ISugarQueryable<EmailRecord> query = _rep.Context.Queryable<EmailRecord>().WhereIF(!string.IsNullOrWhiteSpace(input.FromEmail), (EmailRecord u) => u.FromEmail.Contains(input.FromEmail.Trim())).WhereIF(!string.IsNullOrWhiteSpace(input.Query), (EmailRecord u) => u.Subject.Contains(input.Query.Trim()) || u.Body.Contains(input.Query.Trim()))
			.WhereIF(!string.IsNullOrWhiteSpace(input.ToEmail), (EmailRecord u) => SqlFunc.JsonArrayAny(u.ToEmails, input.ToEmail));
		query = query.OrderBuilder(input);
		return await query.ToPagedListAsync(input.Page, input.PageSize);
	}

	/// <summary>
	/// 发送邮件测试
	/// </summary>
	/// <param name="subject"></param>
	/// <param name="body"></param>
	/// <param name="ownerId"></param>
	/// <param name="toemail"></param>
	/// <returns></returns>
	[HttpPost("/email/sendemailtest")]
	public async Task SendEmailTest(string subject, string body, long ownerId, string toemail)
	{
		Owner owner = await (from w in _rep.Context.Queryable<Owner>()
			where w.Id == ownerId
			select w).FirstAsync();
		if (owner == null)
		{
			throw Oops.Bah("业主不存在");
		}
		EmailConfig config = await _rep.GetFirstAsync((EmailConfig u) => u.TenantId == owner.TenantId);
		EMailUtil util = new EMailUtil();
		MailboxAddress address = new MailboxAddress(owner.Name, toemail);
		await util.SendEmailWithRecord(toEmails: new List<MailboxAddress> { address }, rep: _repRecord, config: config, subject: subject, body: body, userId: ownerId);
	}
}
